import _ from 'lodash';
import { routerRedux } from 'dva/router';
import { Toast } from 'antd-mobile';
import * as vipService from '../services/vipService';
import * as paidVipUtil from '../utils/paidVip';

const delay = (time) => {
  return new Promise((rs) => {
    setTimeout(rs, time);
  });
};
export default {
  namespace: 'vip',
  state: {
    vips: [],
    page: 1,
    totalPageCount: 0,
    totalCount: 0,
    filter: {},
    vipInfo: {},
    label: [],
    labelEdit: '',
    labelTotal: [],
    vipTypes: [],
    selectValue: [2, 0],
    value: '',
  },
  reducers: {
    save(state, { payload: { data, meta, filter } }) {
      return { ...state, vips: [...data], ...meta, filter };
    },
    saveNext(state, { payload: { data, meta, filter } }) {
      return { ...state, vips: [...state.vips, ...data], ...meta, filter };
    },
    saveVipInfo(state, { payload }) {
      return { ...state, vipInfo: payload };
    },
    change(state, { payload }) {
      return { ...state, ...payload };
    },
    updateVipTypes(state, { payload: { data } }) {
      return { ...state, vipTypes: [...data] };
    },
    updateCacheReducers(state, { payload }) {
      // console.log(data);
      return { ...state, ...payload};
    }
  },
  effects: {
    * updateCache({ payload }, { call, put, select }) {
      yield put({ type: 'updateCacheReducers', payload: {...payload}});
    },
    * fetch({ payload: { filter = {}, nextPage = 1 } }, { call, put, select }) {
      const { shopId, branchNo, salemanId, roles } = yield select(state => state.auth.currentUser);
      const nfilter = { shopId };
      if (branchNo) nfilter.branch_no = branchNo;
      if (roles.indexOf('salesman') !== -1) nfilter.saleman_id = salemanId;
      // if (!filter.vip_level) {
      //   filter.vip_level = { $ne: null };
      // }
      const filter1 = _.extend(filter, nfilter);
      const result = yield call(vipService.fetch, nextPage, null, filter1);
      if (shopId === 'qez_1111111') {
        result.data.forEach((v) => {
          const tel = v.vip_tel || v.mobile;
          v.vip_tel = _.padEnd(tel.substr(0, 7), 11, '*');
          v.mobile = _.padEnd(tel.substr(0, 7), 11, '*');
        });
      }
      yield put({ type: 'save', payload: { ...result, filter: filter1 } });
    },
    * fetchNext({ payload }, { call, put, select }) {
      const { page, filter } = yield select(state => state.vip);
      const nextPage = page + 1;
      const result = yield call(vipService.fetch, nextPage, null, filter);
      yield put({ type: 'saveNext', payload: { ...result, filter } });
    },
    * fetchVipInfo({ payload: { cardNo } }, { call, put, select }) {
      const { shopId } = yield select(state => state.auth.currentUser);
      const result = yield call(vipService.fetchVipInfo, shopId, cardNo);
      yield put({ type: 'saveVipInfo', payload: result.data });
    },
    * stick({ payload: { _id, is_stick } }, { call, put, select }) {
      const result = yield vipService.updateStick(_id, is_stick);
      if (result.data.ok) {
        const filter = {};
        const { shopId, branchNo, salemanId } = yield select(state => state.auth.currentUser);
        const nfilter = { shopId };
        if (branchNo) nfilter.branch_no = branchNo;
        if (salemanId) nfilter.saleman_id = salemanId;
        if (!filter.vip_level) {
          filter.vip_level = { $ne: null };
        }
        const filter1 = _.extend(filter, nfilter);
        const ret = yield call(vipService.fetch, 1, null, filter1);
        if (shopId === 'qez_1111111') {
          ret.data.forEach((v) => {
            const tel = v.vip_tel || v.mobile;
            v.vip_tel = _.padEnd(tel.substr(0, 7), 11, '*');
            v.mobile = _.padEnd(tel.substr(0, 7), 11, '*');
          });
        }
        yield put({ type: 'save', payload: { ...ret, filter: filter1 } });
      }
    },
    * updateRemarks({ payload: { _id, cardNo, remarks } }, { call, put, select }) {
      const result = yield call(vipService.updateRemarks, _id, remarks);
      yield put({ type: 'task/fetchVipInfo', payload: { cardNo } });
    },
    * create({ payload }, { call, put, select }) {
      Toast.loading();
      const shopOpenid = yield select(state => state.auth.currentUser.shopOpenid);
      const result = yield call(vipService.create, payload);
      if (result && result.data) {
        Toast.hide();
        const vip = result.data;
        if (vip && vip.isPaidVip) {
          const payData = {
            openid: shopOpenid,
            shopId: vip.shopId,
            branchId: vip.branchId || vip.branch_no,
            mobile: vip.mobile,
            cardType: vip.cardType,
          };

          let res;
          try {
            res = yield paidVipUtil.doWxJsPay(payData);

            Toast.hide();

            if (res && res.success) {
              Toast.success('会员创建成功', 3);
              yield delay(2000);
              yield put(routerRedux.goBack());
            } else {
              Toast.fail('付费会员支付失败!', 3);
            }
          } catch (error) {
            Toast.hide();
            Toast.fail('付费会员支付失败!', 3);
          }
        } else {
          Toast.hide();
          Toast.success('会员创建成功', 3);
          yield delay(2000);
          yield put(routerRedux.goBack());
        }
      }
    },
    * reg({ payload }, { call, put }) {
      const result = yield call(vipService.reg, payload);
      if (result) {
        Toast.success('会员创建成功', 2);
        yield delay(1000);
        yield put(routerRedux.goBack());
      }
    },
    * fetchLabel({ payload }, { call, put, select }) {
      const shopId = yield select(state => state.auth.currentUser.shopId);
      const { card_id } = payload;

      const { data } = yield call(vipService.fetchVipLabel, shopId, card_id);

      // let data2=yield call(vipService.fetchShopLabel, shopId);
      // yield put({type:'change', payload:{ label:data, labelTotal:data2.data }});

      yield put({ type: 'change', payload: { label: data } });
    },
    * editLabel({ payload }, { call, put, select }) {
      const shopId = yield select(state => state.auth.currentUser.shopId);
      const { card_id } = payload;

      let label = payload.label || (yield select(state => state.vip.label));
      label = label.filter(item => item.trim().length);
      const obj = { text: label.join(',') };
      const { data } = yield call(vipService.editVipLabel, shopId, card_id, obj);

      if (data.ok) {
        setTimeout(() => {
          Toast.success('修改成功', 1);
        }, 50);

        const taskType = yield select(state => state.routing.locationBeforeTransitions.query.taskType);
        const subType = yield select(state => state.routing.locationBeforeTransitions.query.subType);
        const na = `vips${taskType}${_.isNil(subType) ? '' : subType}`;
        const vips = yield select(state => state.task[na]);
        if (vips.data && vips.data.length) {
          const vip_tags = label.map(item => ({ count: 1, text: item }));
          for (const item of vips.data) {
            if (item.card_no === cardNo) {
              item.vip_tags = vip_tags;
            }
          }
          yield put({ type: 'task/save2', payload: { [na]: vips } });
        }
      } else {
        setTimeout(() => {
          Toast.fail('修改失败', 1);
        }, 50);
      }
    },
    * fetchVipTypes({ payload }, { call, put, select }) {
      const { vipTypes } = yield select(state => state.vip);
      if (vipTypes.length > 0) {
        return;
      }
      const { shopId } = yield select(state => state.auth.currentUser);
      const { data } = yield call(vipService.fetchVipTypes, shopId);
      yield put({ type: 'updateVipTypes', payload: { data } });
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname, query }) => {
        if (pathname === '/labelEdit') {
          const { cardId } = query;
          dispatch({
            type: 'fetchLabel',
            payload: { card_id: cardId },
          });
        }
      });
    },
  },
};
